<script setup lang="ts">
import type { UploadFile } from 'ant-design-vue/es/upload/interface';

import { computed, h, ref } from 'vue';
import { useRoute } from 'vue-router';

import { useVbenModal } from '@vben/common-ui';
import { ExcelIcon, InBoxIcon } from '@vben/icons';
import { cloneDeep } from '@vben/utils';

import { Alert, message, Modal, Tooltip, Upload } from 'ant-design-vue';
import { isFunction } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
// import { downloadImportTemplateFile } from '#/utils/file/download';
import { commonDownloadExcel } from '#/utils/file/download';

interface Props {
  title?: string;
  fileDictName?: string;
  importApi: (value: any, query?: any) => PromiseLike<Record<string, any>>;
  downloadApi: (value: any) => Promise<Blob>;
  downloadFileName?: string;
  alertTitle?: string;
  alertType?: 'error' | 'info' | 'success' | 'warning' | undefined;
  enableTagMatch?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '导入',
  fileDictName: undefined,
  downloadFileName: '',
  alertTitle: undefined,
  alertType: 'info',
  enableTagMatch: false,
});

const emit = defineEmits(['reload']);

const UploadDragger = Upload.Dragger;

const queryData = ref<Record<string, any>>({});

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[600px]',
  onCancel: handleCancel,
  onConfirm: handleSubmit,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }

    const { query } = modalApi.getData() as { query?: Record<string, any> };
    queryData.value = query || {};
  },
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: [
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: '手机', value: 1 },
          { label: '邮箱', value: 2 },
        ],
      },
      fieldName: 'matchType',
      label: '匹配类型',
      rules: 'selectRequired',
    },
    {
      label: '个人标签',
      fieldName: 'labelIds',
      component: 'PersonalTagSelect',
      defaultValue: [],
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
});

const fileList = ref<UploadFile[]>([]);

async function handleSubmit() {
  try {
    modalApi.modalLoading(true);
    if (fileList.value.length !== 1 || !isFunction(props.importApi)) {
      // handleCancel();
      message.warning('请先上传文件');
      return;
    }

    if (props.enableTagMatch) {
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
    }

    const formData = {
      file: fileList.value[0]!.originFileObj as Blob,
    };

    if (props.enableTagMatch) {
      const data = cloneDeep(await formApi.getValues());
      formData.bo = JSON.stringify(data);
    }

    const importApi = props.importApi;
    const { code, data, msg } = await importApi(formData, {
      ...queryData.value,
    });
    console.log(data, msg);
    // let modal = Modal.success;
    if (code === 200) {
      emit('reload', data);
    } else {
      if (!props.enableTagMatch) {
        const modal = Modal.error({
          content: h('div', {
            class: 'max-h-[260px] overflow-y-auto',
            innerHTML: msg, // 后台已经处理xss问题
          }),
          title: '提示',
          closable: false,
          okText: data?.includes('http') ? '查看失败原因' : '好的',
          onOk: () => {
            if (data?.includes('http')) {
              window.open(data, '_blank');
            }
            modal.destroy();
          },
        });
      }
    }
    handleCancel();
  } catch (error) {
    console.warn(error);
    modalApi.close();
  } finally {
    modalApi.modalLoading(false);
  }
}

function handleCancel() {
  modalApi.close();
  fileList.value = [];
  queryData.value = {};
}

const route = useRoute();
const pageName = computed(() => {
  return route.meta.title;
});

async function downloadTemp() {
  // await downloadImportTemplateFile(props.fileDictName);
  await commonDownloadExcel(
    props.downloadApi,
    props.downloadFileName || `${pageName.value}模板`,
  );
}
</script>

<template>
  <BasicModal
    :close-on-click-modal="false"
    :fullscreen-button="false"
    :title="title"
    confirm-text="确定并导入"
  >
    <Alert
      v-if="alertTitle"
      :message="alertTitle"
      :type="alertType"
      show-icon
      banner
      class="mb-[10px]"
    />
    <div v-if="enableTagMatch">
      <BasicForm />
    </div>
    <!-- z-index不设置会遮挡模板下载loading -->
    <!-- 手动处理 而不是放入文件就上传 -->
    <UploadDragger
      v-model:file-list="fileList"
      :before-upload="() => false"
      :max-count="1"
      :show-upload-list="true"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
    >
      <p class="ant-upload-drag-icon flex items-center justify-center">
        <InBoxIcon class="text-primary size-[48px]" />
      </p>
      <p class="ant-upload-text">点击或者拖拽到此处上传文件</p>
    </UploadDragger>
    <div class="mt-2 flex flex-col gap-2">
      <div class="flex items-center gap-2">
        <a-button
          v-if="isFunction(downloadApi)"
          type="link"
          @click="downloadTemp"
        >
          <div class="flex items-center gap-[4px]">
            <ExcelIcon />
            <Tooltip title="温馨提示：红色表头的列为必填项">
              <span>下载模板</span>
            </Tooltip>
          </div>
        </a-button>
        <span class="text-[14px]">允许导入xlsx, xls文件</span>
      </div>
    </div>
  </BasicModal>
</template>
